import {
  mutationWithClientMutationId,
  cursorForObjectInConnection,
  fromGlobalId,
} from 'graphql-relay';
import {GraphQLNonNull, GraphQLString, GraphQLID} from "graphql";
import { Contract, Company } from '../../models';
import CompanyType from "../../types/CompanyType";
import ContractType from "../../types/ContractType";
import { connectionFromType } from '../../connection';

const AddContractMutation = mutationWithClientMutationId({
  name: 'addContract',
  inputFields: {
    name: { type: new GraphQLNonNull(GraphQLString) },
    company_id: { type: GraphQLID },
  },
  outputFields: {
    contractEdge: {
      type: connectionFromType('contract', ContractType).edge,
      resolve: async ({ contractId, company }) => {
        const contracts = await Contract.findAll({
          where: {
            company_id: company.id,
          },
        });
        const contract = contracts.find(o => o.get('id') === contractId);
        return {
          cursor: cursorForObjectInConnection(contracts, contract),
          node: contract,
        };
      },
    },
    company: {
      type: CompanyType,
      resolve: async ({ company }) => company,
    }
  },
  mutateAndGetPayload: async ({ name, company_id }) => {
    const company = await Company.findById(parseInt(fromGlobalId(company_id).id, 10))
    const contract = await Contract.create({
      name,
      company_id: company.id,
    });
    const contractId = contract.dataValues.id;
    return { contractId, company };
  }
});

export default AddContractMutation;
